<?php

class Dispatch extends AppModel {
    var $name = 'Dispatch';

    const DISPATCH_PREFIX = 'ITS';

    var $belongsTo = array(
            'DispatchStatus' => array(
                'fields' => array('id', 'title')
        ),
            'Customer' => array(
                'fields' => array('id', 'cust_no', 'name')
        ),
            'Site' => array(
                'fields' => array('id', 'site_no', 'name')
        ),
            'Warehouse' => array(
                'fields' => array('id', 'name')
        ),
            'User' => array(
                'foreignKey' => 'collector_id',
                'fields' => array('username', 'name')
        )
    );

    var $displayField = 'dispatch_no';

    var $hasMany = array(
        'CustStockIn' => array(
            'dependent'    => true
        )
    );

    var $validate = array(
            'dispatch_date' => array(
                    'rule' => array('date', 'dmy'),
                    'message' => 'Dispatch date is required.',
                    'required' => true,
        ),
            'csd' => array(
                        'rule' => array('notEmpty'),
                        'message' => 'CSD is required.',
                        'required' => true,
        ),
            'quotation_no' => array(
                        'rule' => array('notEmpty'),
                        'message' => 'Quotation no is required.',
                        'required' => true,
        ),
            'pr_no' => array(
                        'rule' => array('notEmpty'),
                        'message' => 'PR no is required.',
                        'required' => true,
        ),
            'deliveree' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Please input delivered to field.',
                    'required' => true,
        ),
            'customer_id' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Customer is required.',
                    'required' => true,
        ),
            'site_id' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Site is required.',
                    'required' => true,
        ),
            'to_warehouse' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Pliease input to warhouse.',
                    'required' => true,
        ),
            'price_adjustment_case' => array(
                    'rule' => 'notEmpty',
                    'message' => 'Price adjustment case is required.',
                    'required' => true,
        ),
    );

    function beforeSave() {
        // Insert
        if (isset($this->data['Dispatch']['dispatch_date'])) {
            $this->data['Dispatch']['dispatch_date'] = $this->dateFormatBeforeSave($this->data['Dispatch']['dispatch_date']);
            $this->data['Dispatch']['quote_price_valid_to'] = $this->dateFormatBeforeSave($this->data['Dispatch']['quote_price_valid_to']);
            $this->data['Dispatch']['price_adjustment_1_date'] = $this->dateFormatBeforeSave($this->data['Dispatch']['price_adjustment_1_date']);
            $this->data['Dispatch']['price_adjustment_1_valid_to'] = $this->dateFormatBeforeSave($this->data['Dispatch']['price_adjustment_1_valid_to']);
            $this->data['Dispatch']['price_adjustment_2_date'] = !empty($this->data['Dispatch']['price_adjustment_2_date'])? $this->dateFormatBeforeSave($this->data['Dispatch']['price_adjustment_2_date']) : null;
            $this->data['Dispatch']['price_adjustment_2_valid_to'] = !empty($this->data['Dispatch']['price_adjustment_2_valid_to'])? $this->dateFormatBeforeSave($this->data['Dispatch']['price_adjustment_2_valid_to']) : null;
            $this->data['Dispatch']['cust_purchase_date'] = $this->dateFormatBeforeSave($this->data['Dispatch']['cust_purchase_date']);
        }
        return true;
    }

    function afterFind($results) {
        foreach ($results as &$dispatch) {
            if (isset($dispatch['Dispatch']['dispatch_date'])) {
                $dispatch['Dispatch']['dispatch_date'] = $this->dateFormatAfterFind($dispatch['Dispatch']['dispatch_date']);
                $dispatch['Dispatch']['quote_price_valid_to'] = $this->dateFormatAfterFind($dispatch['Dispatch']['quote_price_valid_to']);
                $dispatch['Dispatch']['price_adjustment_1_date'] = $this->dateFormatAfterFind($dispatch['Dispatch']['price_adjustment_1_date']);
                $dispatch['Dispatch']['price_adjustment_1_valid_to'] = $this->dateFormatAfterFind($dispatch['Dispatch']['price_adjustment_1_valid_to']);
                // price adjustment case 2 ไม่มี price adjustment 2
                $dispatch['Dispatch']['price_adjustment_2_date'] = !empty($dispatch['Dispatch']['price_adjustment_2_date'])? $this->dateFormatAfterFind($dispatch['Dispatch']['price_adjustment_2_date']) : '-';
                $dispatch['Dispatch']['price_adjustment_2_valid_to'] = !empty($dispatch['Dispatch']['price_adjustment_2_valid_to'])? $this->dateFormatAfterFind($dispatch['Dispatch']['price_adjustment_2_valid_to']) : '-';
                $dispatch['Dispatch']['cust_purchase_date'] = $this->dateFormatAfterFind($dispatch['Dispatch']['cust_purchase_date']);
            }
        }
        return $results;
    }


    /**
     * Custom Query สร้าง Query มาเองให้เป็นรูปแบบที่เหมาะสมสำหรับหน้า print
     * @param int dispatch_id $id
     * @return array data
     */
    function findForPrintByid($id) {
        $this->contain(array('Customer', 'Site', 'Warehouse',
                'CustStockIn' => array('Product' => array('part_no', 'text', 'Unit'), 'CustProductSite')
            )
        );
        $data = $this->findById($id);

        $this->CustStockIn->bindModel(array(
                'hasMany' => array(
                    'ProductSerial' => array(
                        'foreignKey' => 'its_stock_out_id',
                        'conditions' => array(
                            'its_stock_out_type' => CustStockIn::ITS_STOCK_OUT_TYPE
                        )
                    )
                )
            )
        );

        $Product = $this->CustStockIn->Product;
        $PS = $this->CustStockIn->ProductSerial;
        $Location = $PS->Location;

        // วนลูปรายการ CustStockIn
        foreach($data['CustStockIn'] as &$is) {
            // หา Location ที่มีอยู่ใน CustStockIn รายการนี้
            $psLocations = $PS->find('all', array(
                    'fields' => array('DISTINCT location_id'),
                    'conditions' => array(
                        'its_stock_out_id' => $is['id'],
                        'its_stock_out_type' => CustStockIn::ITS_STOCK_OUT_TYPE,
                        'product_id' => $is['product_id']
                    )
                )
            );
            
            // แปะ Location ที่ได้เข้า CustStockIn
            foreach ($psLocations as $psLocation) {
                $Location->contain();
                $location = $Location->findById($psLocation['ProductSerial']['location_id']);

                // option สำหรับ query product serial
                $options = array(
                    'contain' => array(),
                    'conditions' => array(
                        'its_stock_out_id' => $is['id'],
                        'its_stock_out_type' => CustStockIn::ITS_STOCK_OUT_TYPE,
                        'product_id' => $is['product_id'],
                        'location_id' => $psLocation['ProductSerial']['location_id']
                    )
                );
                
                // นับจำนวนที่ stock out ใน location นี้
                $ps_count = $PS->find('count', $options);

                // ถึง เฉพาะ Product Serial ที่มี Serial no หรือ other information (ถ้าไม่มีจะออกมา 1 แถว)
                $options['fields'] = array('DISTINCT serial_no', 'other_information');
                $ps = $PS->find('all', $options);

                $location['deliver_qty'] = $ps_count;
                $location['PS'] = $ps;

                $is['ProductLocation'][] = $location;
            }
        }
        return $data;
    }
    /**
     * Custom Query สร้าง Query มาเองให้เป็นรูปแบบที่เหมาะสมสำหรับหน้า print
     * @param int dispatch_id $id
     * @return array data
     */
    function findForPrintCustomerById($id) {

        $this->CustStockIn->bindModel(array(
                'hasMany' => array(
                    'ProductSerial' => array(
                        'foreignKey' => 'its_stock_out_id',
                        'conditions' => array(
                            'its_stock_out_type' => CustStockIn::ITS_STOCK_OUT_TYPE,
                        )
                    )
                )
            )
        );

        $this->contain(array('Customer', 'Site', 'Warehouse',
                'CustStockIn' => array(
                    'ProductSerial' => array(
                        'conditions' => array(
                            'OR' => array(
                                array('ProductSerial.serial_no !=' => null),
                                array('ProductSerial.other_information !=' => null),
                            )
                        )
                    ), 'Product' => array('part_no', 'text', 'Unit'), 'CustProductSite')
            )
        );
        $data = $this->findById($id);
        return $data;
    }
}
?>
